import React from "react";
import { Card, Menu, message, Icon, Tooltip } from "antd";
import GGEditor, {
	Mind,
	EditableLabel,
	RegisterNode,
	setAnchorPointsState,
} from "gg-editor";
import MindContextMenu from "@/pages/KnowledgeGraph/editDrawer/contextMenu";
import TypeNodeEdit from "@/pages/KnowledgeGraph/editDrawer/typeNode";
import AddAnswer from "@/pages/KnowledgeGraph/editDrawer/addAnswer";
import ToolBar from "@/pages/KnowledgeGraph/editDrawer/toolBar";
import styles from "./guideEdit.less";
import axios from "axios";

class GuideEdit extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			data: {
				id: "0",
				label: "引导话术",
				nodeType: "root",
				children: [],
			},
			selectNode: null,
			eventObj: null,
			editShow: false,
			visible: false,
			fullScreen: false,
			isGuideOption: true,
			answer: "",
			label: "",
			dis: "",
			similarQuestions: [],
			addDisabled: false,
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	componentWillReceiveProps(nextProps, nextContext) {
		const { data } = nextProps;
		this.setState({
			data,
		});
	}

	seeNodeDetail = (e) => {
		e.preventDefault();
		let { selectNode, eventObj, addDisabled } = this.state;

		if (e.item) {
			selectNode = e.item._cfg.model;

			if (
				selectNode.nodeType == 1 &&
				selectNode.children != undefined &&
				selectNode.children.length > 0
			) {
				addDisabled = true;
			} else {
				addDisabled = false;
			}
			eventObj = e;
			this.setState({
				selectNode,
				eventObj,
				editShow: false,
				addDisabled,
			});
		} else {
			this.setState({
				selectNode: null,
				eventObj: null,
				editShow: false,
				addDisabled,
			});
		}
	};

	canvasClickHandle = (title) => {
		this.hideContextMenu();
		this.setState(
			{
				editShow: false,
			},
			() => {
				if (title) {
					// this.graphNode.graph.clear();
					// this.props.onClose();
					this.graphNode.graph.updateItem(this.state.selectNode.id, {
						label: title,
					});
					this.graphNode.graph.fitCenter();
				}
			}
		);
	};

	hideContextMenu = () => {
		this.setState({
			// selectNode: null,
			eventObj: null,
		});
	};

	menuClickhandle = (e) => {
		const that = this;
		switch (e.key) {
			case "addChild":
				return that.nodeAddChild();
			case "addQuestion":
				return that.nodeAddQuestion();
			case "addAnswer":
				return that.nodeAddAnswer();
			case "edit":
				return that.nodeEdit();
			case "del":
				return that.nodeDel();
			default:
				return "";
		}
		this.hideContextMenu();
	};

	nodeAddChild = () => {
		let { selectNode } = this.state;
		this.addNode(selectNode, "选项", 1);
	};

	nodeAddQuestion = () => {
		let { selectNode } = this.state;
		this.addNode(selectNode, "引导话术", 0);
	};

	nodeAddAnswer = () => {
		let { selectNode } = this.state;
		this.addNode(selectNode, "答案", 2);
	};

	nodeEdit = () => {
		const that = this;
		const { selectNode } = this.state;
		// if (selectNode.nodeType === 'second' || selectNode.nodeType === 'root') {
		if (selectNode.nodeType === 1 || selectNode.nodeType === 0) {
			that.setState(
				{
					editShow: true,
				},
				() => {
					this.getAnswer(selectNode);
				}
			);
		}
		if (selectNode.nodeType === 2) {
			that.setState(
				{
					visible: true,
				},
				() => {
					this.getAnswer(selectNode);
				}
			);
		}
		this.hideContextMenu();
	};

	nodeDel = () => {
		let { selectNode, data } = this.state;
		const token =
			window.localStorage.getItem("robot_token") == undefined
				? ""
				: window.localStorage.getItem("robot_token");
		const headData = {
			"Content-Type": "application/json",
			Authorization: "Bearer " + token,
		};
		axios
			.post(
				"/knowledge-api/processGuide/removeProcessGuide",
				{ id: selectNode.id },
				{ headers: headData }
			)
			.then((ret) => {
				let res = null;
				if (ret.data.data) {
					res = ret.data.data;
				} else {
					res = ret.data;
				}
				this.graphNode.graph.removeChild(selectNode.id);
				// this.graphNode.graph.fitCenter();
				// this.graphNode.graph.fitView();
				this.hideContextMenu();
			});
	};

	getAnswer(selectNode) {
		const token =
			window.localStorage.getItem("robot_token") == undefined
				? ""
				: window.localStorage.getItem("robot_token");
		const headData = {
			"Content-Type": "application/json",
			Authorization: "Bearer " + token,
		};
		axios
			.get(
				"/knowledge-api/processGuide/getProcessQuestion?id=" + selectNode.id,
				{
					headers: headData,
				}
			)
			.then((ret) => {
				let res = null;
				if (ret.data.data) {
					res = ret.data.data;
				} else {
					res = ret.data;
				}
				if (res.nodeType == 1 || res.nodeType == 0) {
					this.TypeNodeEdit.setNode(res);
					// this.setState({
					//   label:res.label,
					//   dis:res.question[0].dis,
					//   similarQuestions:res.question[1].similarQuestions
					// })
				}
				if (res.nodeType == 2) {
					this.setState({ answer: res.answer });
				}
			});
	}

	getUuid = () => {
		function S4() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}
		return (
			S4() +
			S4() +
			"-" +
			S4() +
			"-" +
			S4() +
			"-" +
			S4() +
			"-" +
			S4() +
			S4() +
			S4()
		);
	};

	closeDraw = () => {
		this.setState({
			visible: false,
			answer: "",
		});
	};

	save = (val) => {
		const { selectNode } = this.state;
		let obj = {
			processName: selectNode.label,
			id: selectNode.id,
			processType: selectNode.nodeType,
			answer: val,
		};
		const token =
			window.localStorage.getItem("robot_token") == undefined
				? ""
				: window.localStorage.getItem("robot_token");
		const headData = {
			"Content-Type": "application/json",
			Authorization: "Bearer " + token,
		};
		axios
			.post("/knowledge-api/processGuide/editProcessGuide", obj, {
				headers: headData,
			})
			.then((ret) => {
				let res = null;
				if (ret.data.data) {
					res = ret.data.data;
				} else {
					res = ret.data;
				}
				message.info(res.msg);
			});
		this.closeDraw();
	};

	mindFitview = (e) => {
		this.graphNode.graph.fitView();
	};

	mindFullScreen = () => {
		let { fullScreen } = this.state;
		fullScreen = !fullScreen;
		this.setState({
			fullScreen,
		});

		if (fullScreen) {
			this.graphNode.graph.changeSize(952, window.innerHeight - 50);
		} else {
			this.graphNode.graph.changeSize(952, 500);
		}
		this.graphNode.graph.fitView();
	};

	addNode(selectNode, type, nodeType) {
		const token =
			window.localStorage.getItem("robot_token") == undefined
				? ""
				: window.localStorage.getItem("robot_token");
		const headData = {
			"Content-Type": "application/json",
			Authorization: "Bearer " + token,
		};
		let obj = {
			processName: type,
			atlasNodesId: selectNode.atlasNodesId,
			processType: nodeType,
			parentId: selectNode.id,
		};
		axios
			.post("/knowledge-api/processGuide/saveProcessGuide", obj, {
				headers: headData,
			})
			.then((ret) => {
				let res = null;
				if (ret.data.data) {
					res = ret.data.data;
				} else {
					res = ret.data;
				}
				if (res.nodeId) {
					let nodeColor = "";
					let fontColor = "";
					let borderColor = "";
					switch (nodeType) {
						case 0:
							nodeColor = "#0099FF";
							break;
						case 1:
							nodeColor = "#66CC66";
							break;
						case 2:
							nodeColor = "#fff";
							fontColor = "red";
							borderColor = "red";
							break;
					}
					const newNode = {
						id: res.nodeId,
						side: "right",
						label: type,
						nodeType: nodeType,
						nodeColor: nodeColor,
						atlasNodesId: selectNode.atlasNodesId,
						fontColor: fontColor,
						borderColor,
					};

					this.graphNode.graph.addChild(newNode, selectNode.id);
					// this.graphNode.graph.fitCenter();
					// this.graphNode.graph.fitView();
					this.hideContextMenu();
				}
			});
	}

	onNodeDbClick = (e) => {
		let item = e.item.getModel();
		this.setState({
			selectNode: item,
		});
	};

	onNodeClick = (e) => {
		let item = e.item.getModel();
		this.setState(
			{
				selectNode: item,
			},
			() => {
				if (item.nodeType == 2) {
					this.nodeEdit();
				}
			}
		);
	};

	setAnswer = (answer) => {
		this.setState({
			answer,
		});
	};
	render() {
		return (
			<div>
				<div style={{ margin: 10, display: "flex" }}>
					<h4>
						流程引导
						<Tooltip
							placement='top'
							title='双击节点，点击下方保存可修改节点名称'
							arrowPointAtCenter>
							<Icon
								style={{ fontSize: 14, marginLeft: "10px", color: "#FFCC33" }}
								type='info-circle'
							/>
						</Tooltip>
					</h4>
					<div className={styles.example}>
						<span className={styles.example1}></span>引导话术
						<span className={styles.example2}></span>选项
						<span className={styles.example3}></span>答案
					</div>
				</div>
				<div>
					<GGEditor
						className={this.state.fullScreen ? styles.fullscreen : styles.body}>
						<ToolBar
							fitView={this.mindFitview}
							fullScreen={this.mindFullScreen}
							isFullScreen={this.state.fullScreen}
						/>
						<Mind
							className={styles.graph}
							data={this.state.data}
							onContextMenu={this.seeNodeDetail}
							onCanvasClick={() => this.canvasClickHandle()}
							onCanvasDrag={() => this.canvasClickHandle()}
							onNodeDoubleClick={this.onNodeDbClick}
							onNodeClick={this.onNodeClick}
							ref={(e) => (this.graphNode = e)}
							graphConfig={{
								lineAppendWidth: 2,
								defaultNode: { type: "customDomNode" },
								layout: {
									type: "compactBox",
									direction: "LR",
									getId: function getId(d) {
										return d.id;
									},
									getHeight: function getHeight() {
										return 16;
									},
									getWidth: function getWidth() {
										return 160;
									},
									getVGap: function getVGap() {
										return 40;
									},
									getHGap: function getHGap() {
										return 40;
									},
								},
							}}
						/>
						{this.state.selectNode && this.state.selectNode.nodeType == 2 ? (
							""
						) : (
							<EditableLabel />
						)}
						<MindContextMenu
							node={this.state.selectNode}
							eventObj={this.state.eventObj}
							menuClick={this.menuClickhandle}
							disabled={this.state.addDisabled}
						/>
						<TypeNodeEdit
							visible={this.state.editShow}
							node={this.state.selectNode}
							close={(title) => this.canvasClickHandle(title)}
							isGuideOption={this.state.isGuideOption}
							onRef={(ref) => {
								this.TypeNodeEdit = ref;
							}}
						/>
						<AddAnswer
							content={this.state.answer}
							onClose={this.closeDraw}
							visible={this.state.visible}
							save={this.save.bind(this)}
							addAnswer={this.props.add}
						/>
						<RegisterNode
							name='customDomNode'
							config={{
								getCustomConfig(model) {
									const { nodeColor } = model;
									const { fontColor } = model;
									const { borderColor } = model;
									return {
										size: [80, 40],
										radius: 20,
										wrapperStyle: {
											fill: nodeColor ? nodeColor : "#5E6A7D",
										},
										contentStyle: {
											fill: nodeColor ? nodeColor : "#5E6A7D",
											stroke: borderColor ? borderColor : "",
										},
										labelStyle: {
											fill: fontColor ? fontColor : "#FFFFFF",
										},
									};
								},
								// draw(cfg, group) {
								//
								//   const { label, nodeColor, fontColor, borderColor } = cfg;
								//   let rect = group.addShape('rect', {
								//     attrs: {
								//       fill: nodeColor ? nodeColor : '#5E6A7D',
								//       stroke: borderColor ? borderColor : '',
								//       radius: 5,
								//       width: 80,
								//       height: 40,
								//     },
								//     name: 'title-box',
								//   });
								//   group.addShape('text', {
								//     attrs: {
								//       text: cfg.label,
								//       textBaseline: 'top',
								//       fontSize: 18,
								//       cursor: 'pointer',
								//       fill: fontColor ? fontColor : '#FFFFFF',
								//     },
								//     name: 'rect-shape',
								//   });
								//   return rect;
								// },
								getAnchorPoints() {
									return [
										[0.5, 0],
										[0.5, 1],
										[0, 0.5],
										[1, 0.5],
									];
								},
							}}
							extend='bizFlowNode'
						/>
						<RegisterNode
							name='customInternalNode'
							config={{
								setState(name, value, item) {
									setAnchorPointsState.call(
										this,
										name,
										value,
										item,
										(item, anchorPoint) => {
											const { width, height } = item.getKeyShape().getBBox();

											const [x, y] = anchorPoint;

											return {
												x: width * x - width / 2,
												y: height * y - height / 2,
											};
										},
										(item, anchorPoint) => {
											const { width, height } = item.getKeyShape().getBBox();

											const [x, y] = anchorPoint;

											return {
												x: width * x - width / 2,
												y: height * y - height / 2,
											};
										}
									);
								},
								getAnchorPoints() {
									return [
										[0.5, 0],
										[0.5, 1],
										[0, 0.5],
										[1, 0.5],
									];
								},
							}}
							extend='ellipse'
						/>
					</GGEditor>
				</div>
			</div>
		);
	}
}

export default GuideEdit;
